#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct book
{
    char bookname[20];
    int bookprice;
}book_t;

//节点类型
typedef struct node
{
    //前驱指针
    struct node * before;
    //数据部分
    void* data;
    //后继指针
    struct node* after;
}node_t;

//初始化
node_t *initlist();
//尾插
int tail_insert(node_t *list,book_t *data);
//修改指定结点
int change_index_list(node_t *list,int index);
//遍历
int show_list(node_t *list);

//编写函数实现修改第index个节点的数据操作
int main(int argc, char const *argv[])
{
    node_t *list=initlist();
    book_t book1={"西游记",45};
    book_t book2={"红楼梦",50};
    book_t book3={"水浒传",55};
    book_t book4={"三国演义",60};
    tail_insert(list,&book1);
    tail_insert(list,&book2);
    tail_insert(list,&book3);
    tail_insert(list,&book4);
    show_list(list);

    change_index_list(list,2);
    show_list(list);
    return 0;
}

//初始化
node_t *initlist()
{
    node_t *head=(node_t *)malloc(sizeof(book_t));
    if(head==NULL)
    {
        printf("head malloc failed\n");
        return NULL;
    }
    head->data=NULL;
    head->before=head->after=head;
    return head;
}
//尾插
int tail_insert(node_t *list,book_t *data)
{
    if(list==NULL||data==NULL)
    {
        printf("error\n");
        return -1;
    }
    node_t *newnode=(node_t *)malloc(sizeof(node_t));
    if(newnode==NULL)
    {
        printf("newnode malloc failed\n");
        return -1;
    }
    // book_t *newdata=(book_t *)malloc(sizeof(book_t));
    // if(newdata==NULL)
    // {
    //     printf("newdata malloc failed\n");
    //     free(newnode);
    //     return -1;
    // }
     //memcpy(newnode,data,sizeof(book_t));
    newnode->data=data;
    
    node_t *tail=list->before;//指向尾结点
    tail->after=newnode;
    newnode->before=tail;
    newnode->after=list;
    list->before=newnode;

}
//修改指定结点
int change_index_list(node_t *list,int index)
{
    if(list==NULL)
    {
        printf("list is error\n");
        return -1;
    }
    if(index<1)
    {
        printf("index is error\n");
        return -1;
    }
    node_t *phead=list->after;
    int i=1;
    while(phead!=list)
    {
        if(i<index)
        {
            phead=phead->after;
            i++;
        }
        else
        {
            break;
        }
    }
    if(phead==list)
    {
        printf("index is large\n");
        return -1;
    }
    printf("请输入新名字:");
    book_t *book=(book_t *)phead->data;
    scanf("%s",book->bookname);
    printf("请输入新价格:");
    scanf("%d",&book->bookprice);
    return 0;
}

//遍历
int show_list(node_t *list)
{
    node_t *phead=list->after;
    while(phead!=list)
    {
        book_t *book=(book_t *)phead->data;
        printf("书名:%s\t价格:%d\n",book->bookname,book->bookprice);
        phead=phead->after;
    }
    return 0;
}